from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QGraphicsItem, QGraphicsScene, QGraphicsView

import math

class Butterfly(QGraphicsItem):
    def __init__(self):
        super(Butterfly, self).__init__()
        self.pix_up = QPixmap()
        self.pix_down = QPixmap()
        self.pix_up.load("butterfly.png")
        self.pix_down.load("butterfly_down.png")

        self.up = True

        self.aa = QTimer()
        self.aa.timeout.connect(self.slottimer)
        self.aa.start(500)

        self.angle = 0
        self.dx = 0
        self.dy = 0


    def boundingRect(self):
        adjust = 2
        return QRectF(-self.pix_up.width() / 2 - adjust, -self.pix_up.height() / 2 - adjust,
                       self.pix_up.width() + 2 * adjust,  self.pix_up.height() + 2 * adjust)

    def paint(self, painter, option, widget):

        if self.up:
            painter.drawPixmap(self.boundingRect().topLeft(), self.pix_up)
            self.up = not self.up
            print(self.up)
        else:
            painter.drawPixmap(self.boundingRect().topLeft(), self.pix_down)
            self.up = not self.up
            print(self.up)

    def slottimer(self):

        edgex = self.scene().sceneRect().right() + self.boundingRect().width() / 2
        edgetop = self.scene().sceneRect().top() + self.boundingRect().height() / 2
        edgebottom = self.scene().sceneRect().bottom() + self.boundingRect().height() / 2

        if (self.pos().x() >= edgex):
            self.setPos(self.scene().sceneRect().left(), self.pos().y())
        if (self.pos().y() <= edgetop):
            self.setPos(self.pos().x(), self.scene().sceneRect().bottom())
        if (self.pos().y() >= edgebottom):
            self.setPos(self.pos().x(), self.scene().sceneRect().top())


        self.angle += (qrand() % 10) / 20.0
        self.dx = math.fabs(math.sin(self.angle * math.pi) * 10.0)
        self.dy = (qrand() % 20) - 10.0
        self.setPos(self.mapToParent(self.dx+50, self.dy-50))

class MainWidget(QWidget):
    def __init__(self):
        super(MainWidget, self).__init__()

        self.scene = QGraphicsScene()
        self.scene.setSceneRect(-200, -200, 400, 400)

        self.butterfly = Butterfly()
        #self.butterfly.setPos(-100, 0)

        self.scene.addItem(self.butterfly)

        self.view = QGraphicsView()
        self.view.setScene(self.scene)
        self.view.setMinimumSize(400, 400)

        self.mainlayout = QtWidgets.QHBoxLayout()
        self.mainlayout.addWidget(self.view)
        self.setLayout(self.mainlayout)

        self.setWindowTitle(self.tr("飞舞的蝴蝶"))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    mainwindow = MainWidget()
    mainwindow.show()
    sys.exit(app.exec_())